package com.lepu.app.fun.my;

import java.util.HashMap;
import java.util.Map;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.MyStoreUtil;
import com.app.utils.ObserverConst;
import com.app.utils.PlaySoundXfUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.BrowserWebChromeClient;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.Reachability;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.lepu.app.fun.my.bean.BeanMyArticle;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

/**
 * 文章详情 视频详情 通用
 * @author wxd
 *
 */
@SuppressLint("JavascriptInterface")
public class MyArticleInfoActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest{

	private FrameLayout mVideoFullView;// 全屏时视频加载view
	private View mCustomVideoView;
	private WebChromeClient.CustomViewCallback mCustomViewCallback;
	private MyWebChromeClient mMyWebChromeClient;
	private boolean mFirstEnterWebView = false;

	private static final String REQUEST_INFO = "request_info";
	
	public static final String GOTO_HST_MALL = "goto::hstMall?url=";
	public static final String GOTO_CREDITS_MALL = "goto::creditsMall?url=";

	private BeanMyArticle mBeanMyArticle = null;
	private String mArticleID = null;
	private boolean mReadIsHidden = false;//13活动文章详情 跳转隐藏朗读

	private RelativeLayout mContentLayout = null;
	private TextView mCollectStateTextView = null;
	private TextView mHelpStateTextView = null;
	private TextView mReadingTextView = null;
	private WebView mWebView = null;
	private ProgressBar mProgressBar = null;

	private boolean mCurrentOpeCollect = false;
	private boolean mCurrentOpeHelp = false;
	
	private PlaySoundXfUtil mPlaySound;
	
	CustomTopBarNew mTopbar = null;
	private boolean mIsVideo = false;
	private int mPosition = 0;
	
	private boolean isFinish = false;
	
	private String readString = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_article_info_activity);

		init();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onResume() {
		mWebView.onResume();
		mWebView.resumeTimers();
		super.onResume();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onPause() {
		mWebView.onPause();
		mWebView.pauseTimers();
		super.onPause();
	}

	@Override
	public void onDestroy() {

		mPlaySound.stopSound();

		mVideoFullView.removeAllViews();
		mWebView.loadUrl("about:blank");
		mWebView.stopLoading();
		mWebView.setWebChromeClient(null);
		mWebView.setWebViewClient(null);
		mWebView.destroy();
		mWebView = null;

		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	@SuppressLint("SetJavaScriptEnabled")
	private void init() {
		// topbar
		mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
		mTopbar.setTopbarTitle("");
		mTopbar.setonTopbarNewLeftLayoutListener(this);
		
		mPlaySound = new PlaySoundXfUtil(MyArticleInfoActivity.this);

		mArticleID = getIntent().getStringExtra("ArticleID");
		mPosition = getIntent().getIntExtra("position", 0);

		mCollectStateTextView = (TextView) findViewById(R.id.collectStateTextView);
		mHelpStateTextView = (TextView) findViewById(R.id.helpStateTextView);
		mReadingTextView = (TextView) findViewById(R.id.readingTextView);

		mContentLayout = (RelativeLayout) findViewById(R.id.contentLayout);
		mContentLayout.setVisibility(View.GONE);

		mProgressBar = (ProgressBar) findViewById(R.id.topProgressBar);

		mWebView = (WebView) findViewById(R.id.webView);
		mWebView.setWebViewClient(new CustomWebClient());
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");

		mVideoFullView = (FrameLayout) findViewById(R.id.videoFullView);
		mMyWebChromeClient = new MyWebChromeClient();
		mWebView.setWebChromeClient(mMyWebChromeClient);

		Utils.initWebViewSettings(mWebView,true);

		//
		requestInfo();
	}

	private void initData() {
		if(mWebView == null)
		{
			return;
		}
		mContentLayout.setVisibility(View.VISIBLE);
		
		LinearLayout topArticleLayout = (LinearLayout) findViewById(R.id.topArticleLayout);

		int LinkTargetType = UtilityBase.parseInt(mBeanMyArticle.LinkTargetType);
		if(LinkTargetType == 13){
			//活动文章
			mReadIsHidden = true;
			mReadingTextView.setVisibility(View.GONE);
		}

		int acid = UtilityBase.parseInt(mBeanMyArticle.ACID);
		if(acid == 24 || acid == 209)
		{
			//视频详情
			mIsVideo = true;
			mTopbar.setTopbarTitle("视频详情");
			String videoUrl = Setting.getVideoDetailUrl(mArticleID,LoginUtil.getUserId());
			mWebView.loadUrl(videoUrl);
			
			topArticleLayout.setVisibility(View.GONE);
			mHelpStateTextView.setVisibility(View.GONE);
			mReadingTextView.setVisibility(View.GONE);
			mReadIsHidden = true;
			
			updateCollect(true, mBeanMyArticle.HasCollect);

			int viewCount = UtilityBase.parseInt(mBeanMyArticle.ViewCount);
			viewCount ++;
			mBeanMyArticle.ViewCount = String.valueOf(viewCount);
			//视频集萃更新
			ObserverManager.getInstance().notify(ObserverConst.NOTIFY_INDEX_UPDATE_VIDEO_LIST,mPosition,mBeanMyArticle);
		}else{

			//文章详情
			mIsVideo = false;
			mTopbar.setTopbarTitle("文章详情");
			topArticleLayout.setVisibility(View.VISIBLE);
			
			TextView titleTextView = (TextView) findViewById(R.id.titleTextView);
			titleTextView.setText(mBeanMyArticle.ArticleTitle);

			// 文章详细页
			try{
				if(!TextUtils.isEmpty(mBeanMyArticle.ArticleContent))
				{
					mWebView.loadData(mBeanMyArticle.ArticleContent,"text/html; charset=UTF-8", null);
				}
			}catch (Exception e){

			}

			updateTopData();
			updateCollect(true, mBeanMyArticle.HasCollect);
			updateHelp("0");

			notifyCustom();
		}
	}

	
	private void updateTopData()
	{
		TextView timeTextView = (TextView) findViewById(R.id.timeTextView);
		TextView readTextView = (TextView) findViewById(R.id.readTextView);
		TextView likeTextView = (TextView) findViewById(R.id.likeTextView);
		TextView collectCountTextView = (TextView) findViewById(R.id.collectCountTextView);
		
		String time = "";
		try {
			time = DateUtilBase.stringFromDate(DateUtilBase
					.dateFromString(mBeanMyArticle.PublishDate, DateUtilBase.YEAR_MONTH_DAY),
					"MM月dd日");
		} catch (Exception e) {
			time = mBeanMyArticle.PublishDate;
		}
		
		timeTextView.setText(time);
		readTextView.setText("· 阅读  " + mBeanMyArticle.ViewCount + "");
		likeTextView.setText("· 点赞  "+mBeanMyArticle.FavourCount+"");
		collectCountTextView.setText("· 收藏  " + mBeanMyArticle.CollectCount + "");
	}

	private void notifyCustom()
	{
		//百科列表 fragment
		//????
		//首页 文章列表
		ObserverManager.getInstance().notify(ObserverConst.NOTIFY_INDEX_UPDATE_ARTICLE,mPosition,mBeanMyArticle);
	}

	private void updateCollect(boolean firstGo, String state) {
		if (!TextUtils.isEmpty(state) && state.equals("1")) {
			mCollectStateTextView.setSelected(true);
			mCollectStateTextView.setText("已收藏");

			if (!firstGo) {
				MyArticleActivity instanceArticle = (MyArticleActivity) AppManager
						.getAppManager().getActivity(MyArticleActivity.class);
				if (instanceArticle != null) {
					instanceArticle.addItem();
				}
				
				MyVideoActivity instanceVideo = (MyVideoActivity) AppManager
						.getAppManager().getActivity(MyVideoActivity.class);
				if (instanceVideo != null) {
					instanceVideo.addItem();
				}
				
				int count = UtilityBase.parseInt(mBeanMyArticle.CollectCount);
				count ++;
				mBeanMyArticle.CollectCount = String.valueOf(count);
				
				UIHelper.showToast(this, "收藏成功");

				//视频集萃更新
				ObserverManager.getInstance().notify(ObserverConst.NOTIFY_INDEX_UPDATE_VIDEO_LIST, mPosition, mBeanMyArticle);

				notifyCustom();
			}
		} else {
			mCollectStateTextView.setSelected(false);
			mCollectStateTextView.setText("收藏");

			if (!firstGo) {
				MyArticleActivity instanceArticle = (MyArticleActivity) AppManager
						.getAppManager().getActivity(MyArticleActivity.class);
				if (instanceArticle != null) {
					instanceArticle.removeItem();
				}
				
				MyVideoActivity instanceVideo = (MyVideoActivity) AppManager
						.getAppManager().getActivity(MyVideoActivity.class);
				if (instanceVideo != null) {
					instanceVideo.removeItem();
				}
				
				int count = UtilityBase.parseInt(mBeanMyArticle.CollectCount);
				count --;
				mBeanMyArticle.CollectCount = String.valueOf(count);
				
				UIHelper.showToast(this, "取消收藏成功");

				//视频集萃更新
				ObserverManager.getInstance().notify(ObserverConst.NOTIFY_INDEX_UPDATE_VIDEO_LIST, mPosition, mBeanMyArticle);

				notifyCustom();
			}
		}
	}

	private void updateHelp(String state) {
		if (!TextUtils.isEmpty(state) && state.equals("1")) {
			mHelpStateTextView.setSelected(true);
			mHelpStateTextView.setText("已点赞");
			
			int count = UtilityBase.parseInt(mBeanMyArticle.FavourCount);
			count ++;
			mBeanMyArticle.FavourCount = String.valueOf(count);
			
			UIHelper.showToast(this, "点赞成功");

			notifyCustom();
		} else {
			mHelpStateTextView.setSelected(false);
			mHelpStateTextView.setText("点赞");
		}
	}

	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.collectStateTextView:

			boolean flag = LoginUtil.jumpLogin(this);

			if (flag) {
				return;
			}

			if (mCurrentOpeCollect) {
				return;
			}

			mCurrentOpeCollect = true;
			if (view.isSelected()) {
				requestCancelCollect();
			} else {
				requestAddCollect();
			}
			
			UmengHelper.CustomEvent(this, UmengEvent.event_baike_readitlater);
			break;
		case R.id.helpStateTextView:

			boolean flag2 = LoginUtil.jumpLogin(this);

			if (flag2) {
				return;
			}
			
			if (mCurrentOpeHelp) {
				return;
			}

			mCurrentOpeHelp = true;

			if (view.isSelected()) {
				// requestCancelHelp();
			} else {
				requestAddHelp();
			}
			
			UmengHelper.CustomEvent(this, UmengEvent.event_baike_like);
			break;
		case R.id.shareStateTextView:
			share();
			UmengHelper.CustomEvent(this, UmengEvent.event_baike_share);
			break;
		case R.id.readingTextView:
			if(mBeanMyArticle == null){
				return;
			}
			if(!isFinish){
				return;
			}
			mPlaySound.playSound(readString, mReadingTextView);
			break;
		default:
			break;
		}
	}

	private void share() {

		String detailUrl = "";
		if(mIsVideo)
		{
			detailUrl = Setting.getVideoDetailUrl(mArticleID,LoginUtil.getUserId());
		}else{
			detailUrl = Setting.getShareArticleUrl(mArticleID,
					LoginUtil.getUserId(), LoginUtil.getLoginToken());
		}

		String imgPath = SdLocal.getAppIconPath(getApplicationContext());
		if(!TextUtils.isEmpty(mBeanMyArticle.Cover))
		{
			imgPath = mBeanMyArticle.Cover;
		}

		// 调用官方sdk分享，可以各种形式
		ShareLib.Share(this, mBeanMyArticle.ArticleTitle, mBeanMyArticle.ArticleDescription, imgPath, detailUrl,
				false, new CallBack() {
					@Override
					public void callBackSuccess(Object obj) {
						super.callBackSuccess(obj);

						MyNetUtil.getInstance().requestShare(
								MyArticleInfoActivity.this, 1, mArticleID);
					}
				});
	}

	private void requestInfo() {
		String url = Setting.getArticleDetailUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("ArticleID", mArticleID);

		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post_main(url, map, null, this, REQUEST_INFO, true,
				false, true);
	}

	/**
	 * add收藏 请求
	 */
	private void requestAddCollect() {
		int type = 1;
		if(mIsVideo)
		{
			type = 2;
		}
		MyNetUtil.getInstance().requestAddCollect(this, this,
				MyNetUtil.REQUEST_ADD_COLLECT, mBeanMyArticle, type);
	}

	/**
	 * 取消收藏 请求
	 */
	private void requestCancelCollect() {
		int type = 1;
		if(mIsVideo)
		{
			type = 2;
		}
		MyNetUtil.getInstance().requestCancelCollect(this, this,
				MyNetUtil.REQUEST_CANCEL_COLLECT, type, mArticleID);
	}

	/**
	 * add help请求
	 */
	private void requestAddHelp() {

		MyNetUtil.getInstance().requestAddHelp(this, this,
				MyNetUtil.REQUEST_ADD_HELP, mArticleID, 2);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_INFO)) {
			hideProgressDialog();
			mBeanMyArticle = BeanMyArticle.parseDetailInfo((String) data);
			initData();
		} else if (object.equals(MyNetUtil.REQUEST_ADD_COLLECT)) {
			mCurrentOpeCollect = false;
			updateCollect(false, "1");
			updateTopData();
		} else if (object.equals(MyNetUtil.REQUEST_CANCEL_COLLECT)) {
			mCurrentOpeCollect = false;
			updateCollect(false, "0");
			updateTopData();
		} else if (object.equals(MyNetUtil.REQUEST_ADD_HELP)) {
			mCurrentOpeHelp = false;
			updateHelp("1");
			updateTopData();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_INFO)) {
			hideProgressDialog();
		} else if (object.equals(MyNetUtil.REQUEST_ADD_COLLECT)) {
			mCurrentOpeCollect = false;
		} else if (object.equals(MyNetUtil.REQUEST_CANCEL_COLLECT)) {
			mCurrentOpeCollect = false;
		} else if (object.equals(MyNetUtil.REQUEST_ADD_HELP)) {
			mCurrentOpeHelp = false;
		}
	}

	// ======================================================
	class MyWebChromeClient extends WebChromeClient {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			// LogUtilBase.LogD(null, "onProgressChanged===>>" + newProgress);
			mProgressBar.setMax(100);
			if (newProgress < 100) {
				if (mProgressBar.getVisibility() == View.GONE) {
					mProgressBar.setVisibility(View.VISIBLE);
				}
				mProgressBar.setProgress(newProgress);
			} else {
				mProgressBar.setProgress(100);

				Animation animation = AnimationUtils.loadAnimation(MyArticleInfoActivity.this,
						R.anim.lib_broswer_progress);
				// 运行动画
				mProgressBar.startAnimation(animation);
				// 将 spinner 的可见性设置为不可见状态
				mProgressBar.setVisibility(View.GONE);
			}
		}

		//====================
		// private View xprogressvideo;
		// 播放网络视频时全屏会被调用的方法
		@Override
		public void onShowCustomView(View view, CustomViewCallback callback) {
			//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			mWebView.setVisibility(View.INVISIBLE);
			// 如果一个视图已经存在，那么立刻终止并新建一个
			if (mCustomVideoView != null) {
				callback.onCustomViewHidden();
				return;
			}
			mVideoFullView.addView(view);
			mCustomVideoView = view;
			mCustomViewCallback = callback;
			mVideoFullView.setVisibility(View.VISIBLE);
		}

		// 视频播放退出全屏会被调用的
		@Override
		public void onHideCustomView() {
			if (mCustomVideoView == null)// 不是全屏播放状态
				return;

			//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			mCustomVideoView.setVisibility(View.GONE);
			mVideoFullView.removeView(mCustomVideoView);
			mCustomVideoView = null;
			mVideoFullView.setVisibility(View.GONE);
			mCustomViewCallback.onCustomViewHidden();
			mWebView.setVisibility(View.VISIBLE);
		}

		// 视频加载时进程loading
		@Override
		public View getVideoLoadingProgressView() {
//            if (xprogressvideo == null) {
//                LayoutInflater inflater = LayoutInflater
//                        .from(MainActivity.this);
//                xprogressvideo = inflater.inflate(
//                        R.layout.video_loading_progress, null);
//            }
//            return xprogressvideo;
			return null;
		}

	}


	// ======================================================
	class CustomWebClient extends WebViewClient {

		/**
		 * 程序第一次进入加载数据，不会执行这个方法，会执行onPageStarted，于是我在onPageStarted手动执行 shouldOverrideUrlLoading
		 */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			LogUtilBase.LogD(null, "onPageStarted===>>" + url);
			
			if(!mFirstEnterWebView){
				shouldOverrideUrlLoading(mWebView,url);
				mFirstEnterWebView = true;
			}
		}
		
		@Override
		public boolean shouldOverrideUrlLoading(WebView webView, String url) {
			LogUtilBase.LogD(null, "shouldOverrideUrlLoading == >>"+url);
			
			if (!Reachability.checkNetwork(MyArticleInfoActivity.this)) {
                UIHelper.showToast(MyArticleInfoActivity.this, R.string.lib_check_network);
                return true;
            }
			
            if (url.startsWith(GOTO_HST_MALL)) { //跳转到新页面  全商城
            	String splitUrl = url.substring(GOTO_HST_MALL.length());
                MyStoreUtil.getInstance().requestAllMarket(MyArticleInfoActivity.this,splitUrl);
            }else if (url.startsWith(GOTO_CREDITS_MALL)) { //跳转到新页面 积分商城
            	String splitUrl = url.substring(GOTO_CREDITS_MALL.length());
                MyStoreUtil.getInstance().requestMoneyMarket(MyArticleInfoActivity.this,splitUrl);
            } else {
            	webView.loadUrl(url);
            	
            	//test
//            	url = GOTO_CREDITS_MALL + Setting.getMyHelpUrl();
//            	String splitUrl = url.substring(GOTO_CREDITS_MALL.length());
//                MyStoreUtil.getInstance().requestAllMarket(MyArticleInfoActivity.this,splitUrl);
            }
            return true;
		}

		@Override
		public void onPageFinished(final WebView view, final String url) {
			(new Handler()).postDelayed(new Runnable() {
				public void run() {
					if(view == null){
						return;
					}
					view.loadUrl("javascript:window.local_obj.showSource(document.documentElement.innerText);");
				}
			}, 500L);

		}
	}

    final class InJavaScriptLocalObj {
    	
    	@JavascriptInterface
        public void showSource(String html) {

			if(mWebView == null)
			{
				return;
			}

        	if(!isFinish){
        		isFinish = true;
        		readString = html.replaceAll("\n", "").replaceAll(" ","");

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if(TextUtils.isEmpty(readString)|| mReadIsHidden)
						{
							mReadingTextView.setVisibility(View.GONE);
						}else{

							mReadingTextView.setVisibility(View.VISIBLE);

						}
					}
				});
        	}
            
        }
    }
	
}
